package com.jmhy.sdk.fragment;

import android.app.Fragment;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.InputType;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.jmhy.sdk.adapter.UserAccount8Adapter;
import com.jmhy.sdk.common.JiMiSDK;
import com.jmhy.sdk.config.AppConfig;
import com.jmhy.sdk.http.ApiAsyncTask;
import com.jmhy.sdk.http.ApiRequestListener;
import com.jmhy.sdk.model.Guest;
import com.jmhy.sdk.model.LoginMessage;
import com.jmhy.sdk.sdk.JmhyApi;
import com.jmhy.sdk.utils.FragmentUtils;
import com.jmhy.sdk.utils.Seference;
import com.jmhy.sdk.utils.Utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class JmUserSelectLoginAccountFragment8 extends JmBaseFragment implements View.OnClickListener {
    private LinearLayout ll_select_account;

    private TextView tv_title, tv_register_account, tv_input_account, btn_login, tv_version;
    private ListView lv_account_listview;
    private UserAccount8Adapter adapter;
    List<String> moreCountList = new ArrayList<String>();
    List<String> morePwdList = new ArrayList<String>();
    List<String> moreUidList = new ArrayList<String>();
    List<HashMap<String, String>> contentList = new ArrayList<HashMap<String, String>>();
    private String logintoke, account, password;

    private ApiAsyncTask mLoginTask;
    private ApiAsyncTask mAutoLoginTask;

    private boolean isShowList = false;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = null;
        view = inflater.inflate(AppConfig.resourceId(getActivity(), "jm_select_account_login_8", "layout"), container, false);
        view.setClickable(true);
        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
    }

    private void initView() {

        tv_title = getView().findViewById(AppConfig.resourceId(getActivity(), "tv_title", "id"));
        tv_title.setText(AppConfig.appName);

        ll_select_account = getView().findViewById(AppConfig.resourceId(getActivity(), "ll_select_account", "id"));
        ll_select_account.setOnClickListener(this);

        btn_login = getView().findViewById(AppConfig.resourceId(getActivity(), "btn_login", "id"));
        btn_login.setOnClickListener(this);


        tv_register_account = getView().findViewById(AppConfig.resourceId(getActivity(), "tv_register_account", "id"));
        tv_register_account.setOnClickListener(this);

        tv_input_account = getView().findViewById(AppConfig.resourceId(getActivity(), "tv_input_account", "id"));
        tv_input_account.setOnClickListener(this);

        tv_input_account.setInputType(InputType.TYPE_NULL);

        lv_account_listview = getView().findViewById(AppConfig.resourceId(getActivity(), "lv_account_listview", "id"));

        tv_version = getView().findViewById(AppConfig.resourceId(getActivity(), "tv_version", "id"));
        tv_version.setText("v" + AppConfig.sdk_version);
        getData();

        adapter = new UserAccount8Adapter(getActivity(), moreCountList);
        lv_account_listview.setAdapter(adapter);


        lv_account_listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                tv_input_account.setText(moreCountList.get(position));
                password = morePwdList.get(position);
                logintoke = moreUidList.get(position);
                hideListView();
            }
        });
    }

    private void getData() {
        insertDataFromSerference();
        if (mSeference.isExitData()) {
            String temUser = mSeference.getPreferenceData(Seference.ACCOUNT_FILE_NAME, Seference.ACCOUNT_1);
            String temPwd = mSeference.getContentPW(Seference.PASSWORD_1);
            String temUid = mSeference.getPreferenceData(Seference.ACCOUNT_FILE_NAME, Seference.UID_1);
            tv_input_account.setText(temUser);
            password = temPwd;
            logintoke = temUid;


        } else if (mUserinfo.isFile()) {
            insertDataFromFile();
            String temUser = moreCountList.get(0);
            String temPwd = morePwdList.get(0);
            String temUid = moreUidList.get(0);
            tv_input_account.setText(temUser);
            password = temPwd;
            logintoke = temUid;
        }
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == AppConfig.resourceId(getActivity(), "ll_select_account", "id")) {
            hideListView();
        } else if (id == AppConfig.resourceId(getActivity(), "btn_login", "id")) {
            startLogin();
        } else if (id == AppConfig.resourceId(getActivity(), "tv_register_account", "id")) {
            Fragment mUserLoginFragment = FragmentUtils.getJmSkin8Fragment(getActivity(), FragmentUtils.SDK_SELECT_LOGIN_TYPE_TAG);
            replaceFragmentToActivity(getFragmentManager(), mUserLoginFragment, AppConfig.resourceId(getActivity(), "content", "id"));
        } else if (id == AppConfig.resourceId(getActivity(), "tv_input_account", "id")) {
            hideListView();
        }
    }


    /**
     * 从文件中获取数据
     */
    private void insertDataFromFile() {
        // TODO Auto-generated method stub

        moreCountList.clear();
        morePwdList.clear();
        moreUidList.clear();
        Map<String, String> map = new HashMap<>();
        map = mUserinfo.userMap();
        // 判断由于程序出现什么异常导致某些信息没有写入文件系统
        for (int i = 0; i < map.size(); i++) {
            String tU = map.get("user" + i);
            String tempUser = ((tU != null && tU.split(":").length == 3) ? tU.split(":")[0] : "empty");
            String tempPwd = ((tU != null && tU.split(":").length == 3) ? tU.split(":")[1] : "empty");
            String tempUid = ((tU != null && tU.split(":").length == 3) ? tU.split(":")[2] : "empty");

            if (!tempUid.equals("empty") && !tempUser.equals("empty") && !tempPwd.equals("empty")) {
                moreCountList.add(tempUser);
                morePwdList.add(tempPwd);
                moreUidList.add(tempUid);
            }
        }
        for (int i = map.size() - 1; i >= 0; i--) {
            String tU = map.get("user" + i);
            String tempUser = ((tU != null && tU.split(":").length == 3) ? tU.split(":")[0] : "empty");
            String tempPwd = ((tU != null && tU.split(":").length == 3) ? tU.split(":")[1] : "empty");
            String tempUid = ((tU != null && tU.split(":").length == 3) ? tU.split(":")[2] : "empty");
            if (!tempUser.equals("empty") && !tempPwd.equals("empty") && !tempUid.equals("empty")) {
                mSeference.saveAccount(tempUser, tempPwd, tempUid);
            }
        }
    }

    /**
     * 从preference获取数据
     */
    public boolean insertDataFromSerference() {
        moreCountList.clear();
        morePwdList.clear();
        moreUidList.clear();

        contentList = mSeference.getContentList();
        if (contentList == null)
            return false;
        for (int i = 0; i < contentList.size(); i++) {
            moreCountList.add(contentList.get(i).get("account"));
            morePwdList.add(contentList.get(i).get("password"));
            moreUidList.add(contentList.get(i).get("uid"));
        }
        return true;
    }

    private void hideListView() {

        if (!isShowList) {

            if (adapter.getCount() == 0) {
                lv_account_listview.setVisibility(View.GONE);
            } else {
                lv_account_listview.setVisibility(View.VISIBLE);


            }
            isShowList = true;

        } else {

            lv_account_listview.setVisibility(View.GONE);

            isShowList = false;
        }


    }

    private void startLogin() {
        // 登陆
        String username = tv_input_account.getText().toString().trim();


        if (TextUtils.isEmpty(username)) {
            showMsg(AppConfig.getString(getActivity(), "user_hintuser_msg"));
            return;

        }
        if (TextUtils.isEmpty(password)) {
            showMsg(AppConfig.getString(getActivity(), "user_hintpwd_msg"));
            return;
        }

        if (password.equals("~~test")) {
            if (judgeUser(username)) {
                autoLogin(logintoke);
            } else {
                login(username, password);
            }
        } else {
            login(username, password);
        }


    }

    private void login(final String userName, final String passWord) {

        mLoginTask = JmhyApi.get().starusreLogin(getActivity(), AppConfig.appKey, userName, passWord, new ApiRequestListener() {

            @Override
            public void onSuccess(Object obj) {
                // TODO Auto-generated method stub
                if (obj != null) {
                    LoginMessage loginMessage = (LoginMessage) obj;

                    if (loginMessage.getCode().equals("0")) {
                        mSeference.saveAccount(loginMessage.getUname(), "~~test", loginMessage.getLogin_token());
                        AppConfig.saveMap(loginMessage.getUname(), "~~test", loginMessage.getLogin_token());
                        Utils.saveUserToSd(getActivity());
                        wrapaLoginInfo("success", loginMessage.getMessage(), loginMessage.getUname(), loginMessage.getOpenid(), loginMessage.getGame_token());
                        sendData(AppConfig.LOGIN_SUCCESS, obj, handler);

                    } else {

                        sendData(AppConfig.FLAG_FAIL, loginMessage.getMessage(), handler);
                        JiMiSDK.reportRequestErrorAction(getActivity(), "sdk_user_login_error", loginMessage.getCode(), loginMessage.getMessage());

                    }
                } else {
                    sendData(AppConfig.FLAG_FAIL, AppConfig.getString(getActivity(), "http_rror_msg"), handler);
                }
            }

            @Override
            public void onError(int statusCode) {
                // TODO Auto-generated method stub
                sendData(AppConfig.FLAG_FAIL, AppConfig.getString(getActivity(), "http_rror_msg"), handler);
            }
        });
    }


    public void autoLogin(String logintoken) {
        mAutoLoginTask = JmhyApi.get().starlAutoLogin(getActivity(), AppConfig.appKey, logintoken, new ApiRequestListener() {

            @Override
            public void onSuccess(Object obj) {
                // TODO Auto-generated method stub
                if (obj != null) {
                    LoginMessage loginMessage = (LoginMessage) obj;

                    if (loginMessage.getCode().equals("0")) {
                        mSeference.saveAccount(loginMessage.getUname(), "~~test", loginMessage.getLogin_token());
                        AppConfig.saveMap(loginMessage.getUname(), "~~test", loginMessage.getLogin_token());
                        Utils.saveUserToSd(getActivity());
                        wrapaLoginInfo("success", loginMessage.getMessage(), loginMessage.getUname(), loginMessage.getOpenid(), loginMessage.getGame_token());
                        sendData(AppConfig.LOGIN_SUCCESS, obj, handler);

                    } else {

                        sendData(AppConfig.FLAG_FAIL, loginMessage.getMessage(), handler);
                        JiMiSDK.reportRequestErrorAction(getActivity(), "sdk_auto_login_error", loginMessage.getCode(), loginMessage.getMessage());

                    }
                } else {

                    sendData(AppConfig.FLAG_FAIL, AppConfig.getString(getActivity(), "http_rror_msg"), handler);
                }
            }

            @Override
            public void onError(int statusCode) {
                // TODO Auto-generated method stub
                sendData(AppConfig.FLAG_FAIL, AppConfig.getString(getActivity(), "http_rror_msg"), handler);
            }
        });
    }

    private Handler handler = new Handler(Looper.getMainLooper()) {

        @Override
        public void handleMessage(Message msg) {
            if (getActivity() == null || getActivity().isFinishing()) {
                return;
            }
            switch (msg.what) {
                case AppConfig.FLAG_FAIL:

                    String resultmsg = (String) msg.obj;

                    showMsg(resultmsg);
                    Fragment selectAccountLoginFragment = FragmentUtils.getJmSkin8Fragment(getActivity(), FragmentUtils.SDK_LOGIN_TAG);

                    Bundle bundle = new Bundle();
                    bundle.putString("account", tv_input_account.getText().toString());
                    selectAccountLoginFragment.setArguments(bundle);

                    replaceFragmentToActivity(getFragmentManager(), selectAccountLoginFragment, AppConfig.resourceId(getActivity(), "content", "id"));

                    break;

                case AppConfig.LOGIN_SUCCESS:
                    LoginMessage result = (LoginMessage) msg.obj;
                    showUserMsg(result.getUname());
                    AppConfig.USERURL = Utils.toBase64url(result.getFloat_url_user_center());

                    String url = Utils.toBase64url(result.getShow_url_after_login());
                    if (TextUtils.isEmpty(url)) {
                        url = Utils.toBase64url(result.getShow_url_popup());
                    }
                    turnToNotice(url);
                    getActivity().finish();
                    break;
                case AppConfig.FLAG_SHOW_POPWINDOW:
                    break;
                case AppConfig.GUEST_lOGIN_SUCCESS:
                    Guest guest = (Guest) msg.obj;
                    String murl = Utils.toBase64url(guest.getShow_url_after_login());
                    if (TextUtils.isEmpty(murl)) {
                        murl = Utils.toBase64url(guest.getShow_url_popup());
                    }

                    if (!TextUtils.isEmpty(guest.getUpass())) {
                        Bundle args = new Bundle();
                        // Log.i("kk",mobileUser.getMoblie())
                        args.putString("username", guest.getUname());
                        args.putString("upass", guest.getUpass());
                        args.putString("msg", guest.getMessage());
                        args.putString("gametoken", guest.getGame_token());
                        args.putString("openid", guest.getOpenid());
                        args.putString("url", murl);
                        Fragment mJmSetUserFragment = FragmentUtils.getJmSetUserFragment(getActivity(), args);
                        replaceFragmentToActivity(getFragmentManager(), mJmSetUserFragment, AppConfig.resourceId(getActivity(), "content", "id"));
                    } else {
                        wrapaLoginInfo("success", guest.getMessage(), guest.getUname(), guest.getOpenid(), guest.getGame_token());

                        turnToNotice(murl);
                        getActivity().finish();
                    }
                    break;
            }
        }
    };


    @Override
    public void onDestroy() {

        if (mLoginTask != null) {
            mLoginTask.cancel(false);
        }
        if (mAutoLoginTask != null) {
            mAutoLoginTask.cancel(false);
        }

        super.onDestroy();
    }

    public boolean judgeUser(String name) {
        if (mSeference.isExitData()) {
            insertDataFromSerference();
        }
        boolean msg = false;
        for (int i = 0; i < moreCountList.size(); i++) {
            if (name.equals(moreCountList.get(i))) {
                msg = true;

            }
        }

        return msg;
    }

}
